const fs = require('fs')
const path = require('path')
const express = require('express')
// const cache = require('routerDataCache')

const { createServer: createViteServer } = require('vite')
// const axios = require('axios')
const listen = {
	port: 9000,
	ip: '127.0.0.1',
	queue: 511
}

const env = process.env.NODE_ENV

// axios.defaults.adapter = require('axios/lib/adapters/http')

async function initServer(root = process.cwd(), isProd = Boolean(env === 'production')) {
	const app = express()
	const resolve = (p) => path.resolve(__dirname, p)
	const resFile = isProd ? resolve('dist/client/index.html') : resolve('index.html')
	const indexProd = fs.readFileSync(resFile, 'utf-8')
	const manifest = isProd ? require('./dist/client/ssr-manifest.json') : {}

	// 以中间件模式创建 vite 应用，这将禁用 Vite 自身的 HTML 服务逻辑
	// 并让上级服务器接管控制

	// 如果你想使用 Vite 自己的 HTML 服务逻辑（将 Vite 作为
	// 一个开发中间件来使用），那么这里请用 'html'
	var vite
	if (isProd) {
		const serveStatic = require('serve-static')
		app.use(require('compression')())
		app.use(serveStatic(resolve('./dist/client'), { index: false }))
	} else {
		vite = await createViteServer({
			root,
			logLevel: 'error',
			server: {
				middlewareMode: 'ssr',
				watch: {
					// During tests we edit the files too fast and sometimes chokidar
					// misses change events, so enforce polling for consistency
					usePolling: true,
					interval: 100
				}
			}
		})

		app.use(vite.middlewares)
	}

	// const router = express.Router()
	// router.get('/route-cache/:key', (req, res) => {
	// 	let key = req.params.key
	// 	res.setHeader('Content-Type', 'application/json')
	// 	res.send(cache.peek(key))
	// })

	app.use('*', async (req, res) => {
		let url = req.originalUrl

		try {
			let template = indexProd,
				render
			if (isProd) {
				render = require('./dist/server/entry-server.js').render
			} else {
				template = await vite.transformIndexHtml(url, template)
				render = (await vite.ssrLoadModule('/src/entry-server.js')).render
			}

			const { html, links, store, router } = await render(url, manifest)
			const bodyHtml = template
				.replace(`<!--preload-links-->`, links)
				// .replace(`'<vuex-state>'`, store)
				.replace(`window.process = {}`, `window.process.env.NODE_ENV = ${env}`)
				.replace(`<!--ssr-html-->`, html)

			res.status(200).set({ 'Content-Type': 'text/html' }).send(bodyHtml)
		} catch (e) {
			console.error('err=', e)
			vite && vite.ssrFixStacktrace(e)
			res.status(500).send()
		}
	})

	return { app, vite }
}

initServer().then(({ app, vite }) => {
	const { port, ip } = listen
	app.listen(port, ip, () => {
		console.log(`服务指向IP: ${ip}`)
		console.log(`服务监听端口: ${port}`)
		console.log(`服务已启动: http://${ip}:${port}/`)
	})
})

// for test use
exports.createServer = initServer
